<template>
	<n-popover
		class="betslip-input-popover"
		trigger="manual"
		placement="top-end"
		:show="focus && data.isOverLimit">
		<template #trigger>
			<div
				class="h-[26px] px-1 rounded-md flex justify-between items-center bg-bg-2 border duration-200"
				:class="[
					focus ? 'text-t-1 border-primary' : 'text-primary border-border-2',
					betslipStore.tab === BetslipTab.Combo ? 'w-full' : 'w-[120px]'
				]">
				<base-currency :class="focus ? 'text-t-1' : 'text-primary'" />
				<input
					ref="inputRef"
					type="text"
					:value="data?.amount"
					class="w-full flex-1 bg-transparent outline-none border-none text-right text-sm duration-200"
					:class="focus ? 'text-t-1' : 'text-primary'" />
			</div>
		</template>
		<div class="text-white text-sm">
			{{
				$t('betslip.amountRange', [
					fmtAmount(data.minStake, { hideCurrenySymbol: true }),
					fmtAmount(data.maxStake, { hideCurrenySymbol: true })
				])
			}}
		</div>
	</n-popover>
</template>

<script lang="ts" setup>
import { NPopover } from 'naive-ui'
import { BaseCurrency } from '@/components/base'
import { ref, watch, PropType } from 'vue'
import { useAmountInput } from '@/hooks'
import { BetslipBaseType, BetslipTab } from '@/types'
import { fmtAmount } from '@/utils'
import { useBetslipStore } from '@/store'

const props = defineProps({
	data: {
		type: Object as PropType<BetslipBaseType>,
		required: true
	}
})

const emits = defineEmits(['change'])

const betslipStore = useBetslipStore()

const inputRef = ref<HTMLInputElement | null>(null)

const { amount, focus } = useAmountInput(inputRef)

watch(
	() => amount.value,
	() => {
		emits('change', amount.value)
		props.data.isOverLimit =
			(!!props.data?.minStake && props.data.amount < props.data.minStake) ||
			(!!props.data?.maxStake && props.data.amount > props.data.maxStake)
	}
)

watch(
	() => focus.value,
	(val) => {
		if (!val) {
			if (props.data?.minStake && props.data.amount < props.data.minStake) {
				amount.value = props.data.minStake
			} else if (props.data?.maxStake && props.data.amount > props.data.maxStake) {
				amount.value = props.data.maxStake
			}
		}
	}
)
</script>

<style lang="scss">
.betslip-input-popover {
	background: var(--color-danger) !important;
	padding: 4px 8px !important;
	.n-popover-arrow {
		background: var(--color-danger) !important;
	}
}
</style>
